package cn.itsource.ldj.base.service.impl;

import cn.itsource.ldj.base.domain.CodeTypeContants;
import cn.itsource.ldj.base.service.ICodeService;
import cn.itsource.ldj.util.StrUtils;
import cn.itsource.ldj.user.domain.User;
import cn.itsource.ldj.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class CodeServiceImpl implements ICodeService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void sendCode(Map<String, String> map) {

        // 注册的电话
        String phone = map.get("phone");
        // 验证码类型
        String codeType = map.get("codeType");

        // 验证码
        String code = StrUtils.getRandomString(6);

        // 根据手机号码查询数据库，判断是否注册
        User user = userMapper.findByPhone(phone);
        if (user != null && codeType == CodeTypeContants.REGISTER_CODE) {
            throw new RuntimeException("该手机号已注册，请直接登录");
        }

        // 判断是否在60秒内重复发送
        String codeAndTime = (String)redisTemplate.opsForValue().get(codeType + ":" + phone);
        if (codeAndTime != null) {
            // 获取redis中存入的数据，取出时间
            String time = codeAndTime.split(":")[1];

            // 判断是否在一分钟内重复发送请求
            if (System.currentTimeMillis() - Long.valueOf(time) < 5 * 1000) {
                throw new RuntimeException("操作频繁，请勿重复操作");
            }
            // 如果重复发送，且时间在5分钟内，将第一次的验证码赋值给发送的验证码
            code = codeAndTime.split(":")[0];
        }

        // 将验证码存入redis，用手机号做key，5分钟后过期
        redisTemplate.opsForValue().set( codeType + ":"+ phone,code + ":" + System.currentTimeMillis(),5, TimeUnit.MINUTES);

        // 发送短信
//        SendMsgUtils.send(map.get("phone"),"憨批廖望龙：" + code + "5分钟内有效。");
        System.out.println("验证码为：" + code);
        System.out.println("短信不够了");
    }
}
